package com.lan3g.Test.view;

import com.lan3g.Test.controller.RegisterController;
import com.lan3g.Test.pojo.User;
import com.lan3g.Test.util.MD5Util;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet(name = "RegisterServlet",urlPatterns = "/register.jsp")
public class RegisterServlet extends HttpServlet {
    private RegisterController controller
            = new RegisterController();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        password = MD5Util.MD5WithSalt(password);

        String nickname = request.getParameter("nickname");
        String verify = request.getParameter("verify");

        String text = (String) request.getSession()
                .getAttribute("verify");
        // 验证码需要忽略大小写
        if (text == null || !text.equalsIgnoreCase(verify)){
            // 验证码不相等相等,显示错误信息
            fieldMsg(request,response,"验证码错误");
            return;
        }

        // 密码/验证密码不一致


        User user = new User();
        user.setUsername(username)
                .setPassword(password)
                .setNickName(nickname);


        if (controller.register(user)) {
            // 注册成功
            response.sendRedirect("/login.jsp");
        } else {
            fieldMsg(request, response, "注册失败");
        }

    }

    private void fieldMsg(HttpServletRequest request,
                          HttpServletResponse response,
                          String msg) throws ServletException, IOException {
//         String msg = "用户名/密码错误,点击返回登录页面";
        String path = "/register.jsp";
        request.setAttribute("msg", msg);
        request.setAttribute("path", path);
        response.setStatus(302);
        response.setHeader("Refresh", "5;URL=/register.jsp");
        request.getRequestDispatcher("/Exam/msg.jsp")
                .forward(request, response);
    }


    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);

    }
}
